import { URL } from 'url';

import errorCodesBuilder from '../../helpers/errorCodesBuilder';
import { VUL_LEVEL_MAP } from '../../../common/constants';
import { warnEventId } from '../../../common/warnId';
import request from './monitorTaskRequest';

const errorCodes = errorCodesBuilder();

export default (config, server) =>
	async function ssl(job) {
		const api = config.api;
		const { target, collect } = job.data;

		const { hostname: host, port } = new URL(target);
		const payload = {
			host,
			type: collect.pluginCategories.join(','),
		};
		if (port) {
			payload.port = port;
		}

		let result;
		try {
			result = await request({
				job,
				payload,
				api,
				checkInterval: config.checkInterval,
			});
		} catch (err) {
			const error = errorCodes['[04]SSL监测任务创建失败'].from(err);
			server.log.error(
				{
					error,
					job,
					payload,
					api,
					checkInterval: config.checkInterval,
				},
				error.rawMessage
			);
			throw error;
		}

		const pluginCategoryMap = (collect.pluginCategories || []).reduce(
			// eslint-disable-next-line no-sequences
			(obj, x) => ((obj[x] = true), obj),
			{}
		);

		return {
			warnings: (result?.results || []).reduce((arr, x) => {
				const {
					description,
					category,
					impact,
					recommendation,
					risk,
					name,
					display_name: title,
				} = x;
				// 过滤没有开启监测的类别
				if (pluginCategoryMap[category]) {
					arr.push({
						target,
						title,
						description,
						category,
						impact,
						recommendation,
						detail: x,
						id: warnEventId({
							affects: target,
							taskType: 'ssl',
							id: name,
						}),
						level: VUL_LEVEL_MAP[risk],
					});
				}

				return arr;
			}, []),
		};
	};
